var output;
var text_div;

function init() {
	output = document.getElementById('output');
	text_div = document.getElementById('text');
	if (wave && wave.isInWaveContainer()) {
		wave.setStateCallback(stateUpdated);
	}
}
gadgets.util.registerOnLoadHandler(init);

function stateUpdated() {
	if (editing()) {
		stopEditing();
	}
	
	if (!wave.getState().get('text')) {
		text_div.innerHTML = "Click here to edit..."
	} else {
		var text = wave.getState().get('text');
		text_div.innerHTML = text.replace(/\n/g, "<br>");
	}
	
	updateCount();
}

function updateCount() {
	if (editing()) {
		return;
	}
	var text = text_div.innerHTML.replace(/<br>/gi, "\n");

	output.innerHTML = buildOutputString(0, countWords(text), countLines(text));
	gadgets.window.adjustHeight();
}

function countLines(text) {
	return text.split("\n").length;
}

function countWords(text) {
	var result = 0;
	var lines = text.split("\n");
	for (var i = 0; i < lines.length; i++) {
		result += lines[i].split(" ").length;
	}
	return result;
}

function countChars(text) {
	return text.length;
}

function buildOutputString(chars, words, lines) {
	var outputString;
	
	outputString = words + " word";
	if (words > 1) {
		outputString += "s";
	}
	outputString += ", " + lines + " line";
	if (lines > 1) {
		outputString += "s";
	}
	outputString += ".";
	
	return outputString;
}

function editing() {
	if (document.getElementById("input")) {
		return true;
	} else {
		return false;
	}
}

function startEditing() {
	if (editing()) {
		return;
	}
	
	output.style.visibility = "hidden";
	var text = text_div.innerHTML.replace(/<br>/gi, "\n");
	text_div.innerHTML = '<textarea id="input" style="width:100%;height:100%;" onblur="stopEditing()">' + text + '</textarea>';
	document.getElementById("input").focus();
}

function stopEditing() {
	if (!editing()) {
		return;
	}
	
	output.style.visibility = "visible";
	var text = document.getElementById("input").value;
	wave.getState().submitDelta({'text': text});
}